
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
// 使用createSlice创建store模块
const postsStore = createSlice({
  name: "posts", // 模块名称
  // 初始状态
  initialState: {
    posts: [],
    status: "idle",
    error: null,
  },
  // 修改数据的同步方法
  // 使用toolkit来简化 reducers中switch的写法
  // 键名作为action.type, 方法作为对应的 switch case
  reducers: {

  },
  extraReducers(builder) {
    builder
      .addCase(fetchPosts11.pending, (state, action) => {
        state.status = "loading"
      })
      .addCase(fetchPosts11.fulfilled, (state, action) => {
        state.status = "succeeded"
        state.posts = state.posts.concat(action.payload);
      })
      .addCase(fetchPosts11.rejected, (state, action) => {
        state.status = "failed"
        state.error = action.error.message
      })
      .addCase(deletePost.fulfilled, (state, action) => {
        if (!action?.payload.id) {
          console.log("could not delete");
          console.log(action.payload)
          return
        }

        const { id } = action.payload;
        const OldPosts = state.posts.filter(post =>
          post.id !== id)
        state.posts = OldPosts
      })
  }
})

// +++++++++++++++++++++++++++++ 使用createAsyncThunk中间件 +++++++++++++++++++++++++++++++++
const BASE_URL = "https://cn.apihz.cn/api/xinwen/baidums.php?id=88888888&key=88888888";
// createAsyncThunk 接收两个参数: 1. case 关键字最好 slicename/请求 方式定义 2.异步函数 返回promise
export const fetchPosts11 = createAsyncThunk("posts/fetchPosts", async () => {
  const response = await fetch(BASE_URL)
  const data = await response.json();
  console.log(response)
  console.log(response,data)
  return data.data
})
// createAsyncThunk包装后会, 挂载pending fulfilled failed对应的 action creator
console.log('createAsyncThunk...', fetchPosts11.pending())
console.log('createAsyncThunk...', fetchPosts11.fulfilled)
console.log('createAsyncThunk...', fetchPosts11.failed)

export const deletePost = createAsyncThunk("post/deletePost", async (initialPost) => {
  const {id} = initialPost
  try {
      const response = await axios.delete(`${BASE_URL}/${id}`);
      if (response?.status === 200) return initialPost;
      return `${response.status} : ${response.statusText}`;
  } catch (error) {
      return error.message
  }
})
console.log('store_posts...', postsStore )
const { addTodos, deleteTodos, editTodos } = postsStore.actions
export { addTodos, deleteTodos, editTodos }
export default postsStore.reducer;
